package com.demo.juc;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import org.junit.Before;
import org.junit.Test;

public class ExecutorsTest {
	
	private static final int DEFAULT_SIZE = Integer.SIZE - 22;
	
	private static ExecutorService executor =  null;
	
	@Before
	public void before(){
		//拒绝策略:AbortPolicy
		executor = Executors.newFixedThreadPool(DEFAULT_SIZE);
	}

	@Test
	public void test(){
		executor.execute(new Runnable() {
			@Override
			public void run() {
				System.out.println("当前线程号:" + Thread.currentThread().getId() + "正在执行！");
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		});
		
	}
	
	@Test
	public void test2(){
		List<TaskCallable> list =  new ArrayList<TaskCallable>();
		for (int i = 0; i < DEFAULT_SIZE + 5; i++) {
			list.add(new TaskCallable());
		}
		try {
			List<Future<String>> all = executor.invokeAll(list);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	
	@Test
	public void test3(){
		for (int i = 0; i < DEFAULT_SIZE + 5; i++) {
			executor.submit(new TaskRunnable());
		}
	}
	
}

class TaskCallable implements Callable<String>{

	@Override
	public String call() throws Exception {
		System.out.println("当前线程号:" + Thread.currentThread().getId() + "正在执行！");
		try {
			Thread.sleep(10000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		return "执行完成";
	}
	
}


class TaskRunnable implements Runnable{

	@Override
	public void run() {
		System.out.println("当前线程号:" + Thread.currentThread().getId() + "正在执行！");
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	
}
